package mint.modules;

import java.io.InputStream;
import java.util.Formatter;
import java.util.List;

import mint.MintLexer;
import mint.MintParser;
import mint.MintParser.compilationUnit_return;
import mint.modules.generator.CompilationUnitNode;

import org.antlr.runtime.ANTLRInputStream;
import org.antlr.runtime.CommonTokenStream;
import org.antlr.runtime.tree.CommonTree;

public class AssemblyCodeGenerator {
	Formatter output;
	MintLexer lexer;
	MintParser parser;	
	
	
	public AssemblyCodeGenerator(InputStream inputStream, Formatter outputFile) throws Exception {		
		lexer = new MintLexer(new ANTLRInputStream(inputStream));
		CommonTokenStream tokens = new CommonTokenStream(lexer);
		parser = new MintParser(tokens);
		output = outputFile;			
	}
	
	public void generate() throws Exception {		
		compilationUnit_return result = parser.compilationUnit();
		CommonTree tree = (CommonTree)result.getTree();
		
		if (!isSintaxOk())
		{			
			return;
		}
		
		CompilationUnitNode node = new CompilationUnitNode(tree);
		
		
		node.testSemantic();
		List<String> errorList = node.getSemanticErrors();
		
		if (errorList.size() == 0)
		{
			node.emit(output);
			output.format("OK\n");
		}
		else
			for(String err : errorList)
			{
				output.format("%s\n", err);
			}
	}
	
	private boolean isSintaxOk() {
		List<String> errorList = parser.getErrorList();
		
		if (!errorList.isEmpty())
		{
			for(String err : errorList)
			{
				output.format("%s\n", err);
			}
			return false;
		}
		else
			return true;
	}

}
